//
//  server.cpp
//  MyServer
//
//  Created by RJ G on 2025/5/1.
//

#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include "file.h"

const int PORT = 8080;
const int BUFFER_SIZE = 1024;
int g_server;
int g_client;

int main() {
    // 创建socket
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) {
        std::cerr << "Socket创建失败" << std::endl;
        return 1;
    }
    g_server = server_fd;

    // 绑定地址和端口
    sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
    
    if (bind(server_fd, (sockaddr*)&address, sizeof(address)) < 0) {
        std::cerr << "绑定失败" << std::endl;
        return 1;
    }

    // 开始监听
    if (listen(server_fd, 3) < 0) {
        std::cerr << "监听失败" << std::endl;
        return 1;
    }

    std::cout << "服务端启动，监听端口 " << PORT << "..." << std::endl;

    // 接受客户端连接
    sockaddr_in client_addr;
    socklen_t addr_len = sizeof(client_addr);
    int client_socket = accept(server_fd, (sockaddr*)&client_addr, &addr_len);
    if (client_socket < 0) {
        std::cerr << "接受连接失败" << std::endl;
        return 1;
    }
    g_client = client_socket;
    std::string temp;
    bool getFile = false;

    send(client_socket, "hello", 5, 0);
    while (true) {
        // 接收和发送数据
        char buffer[BUFFER_SIZE] = {0};
        int bytes_read = (int)read(client_socket, buffer, BUFFER_SIZE);
        if (bytes_read == 0) {
            break;
        }
        std::cout << "收到消息: " << buffer << std::endl;
        std::string receive = buffer;
        if (receive == "get file" || getFile) {
            if (getFile) {
                getFile = false;
                temp = "start to transport file";
                send(client_socket, temp.c_str(), temp.size(), 0);
                sendFile(receive);
            } else {
                getFile = true;
                temp = "tell me the file name";
                send(client_socket, temp.c_str(), temp.size(), 0);
            }
            continue;
        }

        std::string response = "Hello from server";
        getline(std::cin, response);
        if (response == "exit" || response.size() == 0) {
            response = "exit";
            send(client_socket, response.c_str(), response.size(), 0);
            usleep(100 * 1000);
            break;
        }
        send(client_socket, response.c_str(), response.size(), 0);
        std::cout << "已发送响应" << std::endl;
    }

    // 关闭连接
    close(client_socket);
    close(server_fd);
    return 0;
}
